package com.scwatch.core.thirdapi;


import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.util.HttpRequestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLDecoder;

@Component
public class ThirdHttpRequestUtils {
    private static Logger logger = Logger.getLogger(HttpRequestUtils.class);

    /**
     * httpPost
     *
     * @param url       路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String Param) {
        return httpPost(url, Param, false);
    }

    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url, String Param, boolean noNeedResponse) {
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);

        try {
            if (null != Param) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(Param, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                method.setEntity(entity);
            }

            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (Exception e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }


    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = httpclient.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

//    /**
//     * 上传文件
//     *
//     * @throws ParseException
//     * @throws IOException
//     */
//    public static void postFile(String url, String Param, String filePath) throws ParseException, IOException {
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        try {
//            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
//            HttpPost httpPost = new HttpPost(
//                    "http://11.2.2.223:8081/auth_center/upload");
//            // 把文件转换成流对象FileBody
//            File file = new File(filePath);
//            FileBody bin = new FileBody(file);
//            /*StringBody uploadFileName = new StringBody("my.png",
//                    ContentType.create("text/plain", Consts.UTF_8));*/
//            // 以浏览器兼容模式运行，防止文件名乱码。
//            HttpEntity reqEntity = MultipartEntityBuilder.create()
//                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
//                    .addPart("uploadFile", bin) // uploadFile对应服务端类的同名属性<File类型>
//                    //.addPart("uploadFileName", uploadFileName)// uploadFileName对应服务端类的同名属性<String类型>
//                    .setCharset(CharsetUtils.get("UTF-8")).build();
//
//            httpPost.setEntity(reqEntity);
//
//            System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
//            // 发起请求 并返回请求的响应
//            CloseableHttpResponse response = httpClient.execute(httpPost);
//            try {
//                // 打印响应状态
//                System.out.println(response.getStatusLine());
//                // 获取响应对象
//                HttpEntity resEntity = response.getEntity();
//                if (resEntity != null) {
//                    // 打印响应长度
//                    System.out.println("Response content length: "
//                            + resEntity.getContentLength());
//                    // 打印响应内容
//                    System.out.println(EntityUtils.toString(resEntity,
//                            Charset.forName("UTF-8")));
//                }
//                // 销毁
//                EntityUtils.consume(resEntity);
//            } finally {
//                response.close();
//            }
//        } finally {
//            httpClient.close();
//        }
//    }
}